#!/usr/bin/env python
import subprocess
import re
import time
import random
#该脚本用户取消关注
VERSION = "2023-10-10"

device_name="localhost:5555"
# 检查当前界面是否是快手推荐朋友
def is_acitvity_we_wanted():
    current_activity = subprocess.getoutput(
        "adb -s "+device_name+" shell \"dumpsys activity | grep ActivityRecord | head -n 1\"")
    if "activity.FollowingFriendActivity" in current_activity:
        return True
    return False


# 从UI XML中提取并点击坐标
def read_xml_and_click(ui_name, keyword):
    with open(ui_name, 'r', encoding='utf-8') as file:
        text = file.read()

    array_x = []
    array_y = []

    # 使用正则表达式来匹配 "更多" 后面的 "bounds" 值
    pattern = keyword + r'".*?bounds="(\[\d+,\d+\]\[\d+,\d+\])"'
    boundsMatches = re.findall(pattern, text)

    # 提取匹配到的 "bounds" 值
    for bounds in boundsMatches:
        # 使用正则表达式来匹配坐标值
        pattern = r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]'
        matchesPos = re.match(pattern, bounds)

        if matchesPos:
            x1, y1, x2, y2 = map(int, matchesPos.groups())

            x_point = round((x1 + x2) / 2 + random.randint(0, 4))
            y_point = round((y1 + y2) / 2 + random.randint(2, 4))
            if (x_point > 400):
                array_x.append(x_point)
                array_y.append(y_point)
                print(f'x_point: {x_point}, y_point: {y_point}')
        else:
            print("未找到匹配的 bounds 值")

    for i in range(len(array_x) - 1, 1, -1):
        x = array_x[i]
        y = array_y[i]
        print(f'开始点击更多按钮: {x},  {y}')
        subprocess.run(["adb", "-s", device_name, "shell", "input", "tap", str(x), str(y)])

        # 这里要重新获取一下菜单弹出项，来计算取消关注的位置
        pull_screen_ui('/sdcard/menu.xml')
        read_menu_xml_and_click('menu.xml', '取消关注')

        pull_screen_ui('/sdcard/Unfollow.xml')
        read_unfollow_xml_and_click('Unfollow.xml', '取消关注')

        if is_acitvity_we_wanted() == 0:
            subprocess.run(["adb", "-s", device_name, "shell", "input", "keyevent", "BACK"])
            time.sleep(1)
            if is_acitvity_we_wanted() == 0:
                subprocess.run(["adb", "-s", device_name, "shell", "input", "keyevent", "BACK"])
                time.sleep(1)
            dis = 120 * i + 360
            subprocess.run(["adb", "-s", device_name, "shell", "input", "swipe", "300", str(dis), "310", "200"])
            time.sleep(2)
            print("界面出错，退出点击循环，重新滑动")
            break;

    subprocess.run(["adb", "-s", device_name, "shell", "input", "swipe", "300", "1300", "310", "200"])
    time.sleep(2)


def read_menu_xml_and_click(ui_name, keyword):
    with open(ui_name, 'r', encoding='utf-8') as file:
        text = file.read()

    array_x = []
    array_y = []

    # 使用正则表达式来匹配 "更多" 后面的 "bounds" 值
    pattern = keyword + r'".*?bounds="(\[\d+,\d+\]\[\d+,\d+\])"'
    boundsMatches = re.findall(pattern, text)

    # 提取匹配到的 "bounds" 值
    for bounds in boundsMatches:
        # 使用正则表达式来匹配坐标值
        pattern = r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]'
        matchesPos = re.match(pattern, bounds)

        if matchesPos:
            x1, y1, x2, y2 = map(int, matchesPos.groups())

            x_point = round((x1 + x2) / 2 + random.randint(0, 4))
            y_point = round((y1 + y2) / 2 + random.randint(0, 4))
            if (x_point > 500):
                array_x.append(x_point)
                array_y.append(y_point)
                print(f'找到取消关注菜单点击一下 : {x_point},  {y_point}')
                # 找到取消关注菜单点击一下
                subprocess.run(["adb", "-s", device_name, "shell", "input", "tap", str(x_point), str(y_point)])
                time.sleep(0.5)
        else:
            print("未找到匹配的 bounds 值")


def read_unfollow_xml_and_click(ui_name, keyword):
    with open(ui_name, 'r', encoding='utf-8') as file:
        text = file.read()

    array_x = []
    array_y = []

    # 使用正则表达式来匹配 "更多" 后面的 "bounds" 值
    pattern = keyword + r'".*?bounds="(\[\d+,\d+\]\[\d+,\d+\])"'
    boundsMatches = re.findall(pattern, text)

    # 提取匹配到的 "bounds" 值
    for bounds in boundsMatches:
        # 使用正则表达式来匹配坐标值
        pattern = r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]'
        matchesPos = re.match(pattern, bounds)

        if matchesPos:
            x1, y1, x2, y2 = map(int, matchesPos.groups())

            x_point = round((x1 + x2) / 2 + random.randint(0, 4))
            y_point = round((y1 + y2) / 2 + random.randint(0, 4))
            if (x_point > 300):
                array_x.append(x_point)
                array_y.append(y_point)
                print(f'找到取消关注按钮点击一下 : {x_point}, {y_point}')
                # 找到取消关注菜单点击一下
                subprocess.run(["adb", "-s", device_name, "shell", "input", "tap", str(x_point), str(y_point)])
                time.sleep(1)
        else:
            print("未找到匹配的 bounds 值")


def pull_screen_ui(ui_path):
    if is_acitvity_we_wanted() == 1:
        # 获取当前界面的ui.xml
        uiResult=subprocess.run(["adb", "-s", device_name, "shell", "uiautomator", "dump", ui_path],
                       stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if "ERROR:"  in uiResult.stderr.decode():
            print("uiautomator 出错，请重启手机,程序终止",uiResult.stderr.decode())
            exit(0)
        else:
            subprocess.run(["adb", "-s", device_name, "pull", ui_path], stdout=subprocess.DEVNULL,
                       stderr=subprocess.DEVNULL)


# ADB连接
# ADB连接
def adb_connect():
    # 启动ADB连接
    adb_devices = subprocess.run(["adb", "devices"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if ":5555" not in adb_devices.stdout.decode() or "offline" in adb_devices.stdout.decode() :
        adb_disconnect = subprocess.run(["adb", "disconnect" ], stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        adb_tcpip_5555 = subprocess.run(["adb", "tcpip", "5555" ], stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        adb_tcpip = subprocess.run(["adb", "forward", "tcp:5555", "tcp:5555"], stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        if "refused" in adb_tcpip.stderr.decode():
            print("未连接设备",adb_tcpip)
            exit(0)
        adb_connect = subprocess.run(["adb", "connect", device_name], stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
        if "error" in adb_connect.stdout.decode() or "cannot" in adb_connect.stdout.decode():
            print("adb", "connect", device_name, "出错")
            exit(0)
    else:
        print (adb_devices)

# 启动微信界面
def start_app():
    # 启动快手界面
    if is_acitvity_we_wanted() == 0:
        runresult = subprocess.run(
            ["adb", "-s", device_name, "shell", "am", "start", "com.kuaishou.nebula/com.yxcorp.gifshow.HomeActivity"],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if "not found" in runresult.stdout.decode() or "not found" in runresult.stderr.decode():
            print("启动应用不成功")
            exit(0)


# 主程序
def main():
    adb_connect()
    start_app()
    if is_acitvity_we_wanted() == 1:
        for i in range(20):
            print("滑屏幕", i)
            subprocess.run(["adb", "-s", device_name, "shell", "input", "swipe", "300", "1300", "310", "200"])
            time.sleep(1)
    else:
        print("请先进入\"快手\"再点击\"快手推荐朋友\"再运行该程序")
    time.sleep(3)

    while is_acitvity_we_wanted() == 1:
        for m in range(1001):
            pull_screen_ui("/sdcard/ui.xml")
            read_xml_and_click('ui.xml', '更多')
            time.sleep(1)
            print("退出 for")


if __name__ == "__main__":
    main()